<template>
  <div class="goods-management">
    <!-- 商品列表 -->
    <el-card class="goods-list" shadow="hover">
      <template slot="header">
        <div class="card-header">
          <span>商品列表</span>
          <el-button type="primary" size="mini" @click="addGoods">添加商品</el-button>
        </div>
      </template>
      <el-table :data="goodsList" stripe border>
        <el-table-column prop="goodsName" label="商品名称"></el-table-column>
        <el-table-column prop="goodsImage" label="商品图片">
          <template slot-scope="scope">
            <img :src="scope.row.goodsImage" alt="商品图片" style="width: 100px; height: 50px;">
          </template>
        </el-table-column>
        <el-table-column prop="goodsDescription" label="商品描述"></el-table-column>
        <el-table-column prop="goodsPrice" label="商品价格"></el-table-column>
        <el-table-column prop="tag" label="商品分类"></el-table-column>
        <el-table-column prop="supplierId" label="供应商"></el-table-column>
        <el-table-column prop="goodsInventory" label="商品库存"></el-table-column>
        <el-table-column prop="goodsStatus" label="商品状态" sortable :sort-method="sortGoodsStatus">
          <template slot-scope="scope">
            <el-tag :type="statusTagType(scope.row.goodsStatus)">
              {{ statusText(scope.row.goodsStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="editGoods(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="deleteGoods(scope.row)" >下架</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="tablePage.pageNum"
            :page-size="tablePage.pageSize"
            :page-sizes="pageSizes"
            :total="tablePage.total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
        />
      </div>

    </el-card>

    <!-- 编辑/添加商品弹窗 -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="30%"
        center>
      <el-form ref="goodsForm" :model="currentGoods" label-width="80px">
        <el-form-item label="商品图片" v-if="currentGoods.id == null">
          <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :before-remove="beforeRemove"
                multiple
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="currentGoods.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="goodsDescription">
          <el-input v-model="currentGoods.goodsDescription"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input v-model.number="currentGoods.goodsPrice"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="tag">
          <el-cascader v-model="currentGoods.tag" :options="options" placeholder="请选择商品分类" @change="handleCascaderChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="currentGoods.supplierId" placeholder="请选择供应商">
            <el-option v-for="supplier in suppliers" :key="supplier.id" :value="supplier.id" :label="supplier.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品库存" prop="goodsInventory">
          <el-input v-model.number="currentGoods.goodsInventory"></el-input>
        </el-form-item>
        <el-form-item label="商品状态" prop="goodsStatus">
          <el-radio-group v-model="currentGoods.goodsStatus">
            <el-radio label="1">上架</el-radio>
            <el-radio label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveGoods">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryGoodsPage,
  insertGoods,
  updateGoods, querySupplier
} from '../../../api/index'
export default {
  data() {
    return {
      goodsList: [], // 商品列表数据
      suppliers:[], // 供应商信息
      dialogVisible: false, // 编辑/添加商品弹窗是否可见
      currentGoods: {
      }, // 当前编辑的商品对象
      dialogTitle: '',
      fileList: [],
      options: [
        {
          value: '普通专区',
          label: '普通专区',
          children: [
            {
              value: '服饰鞋物',
              label: '服饰鞋物'
            },
            {
              value: '花卉盆栽',
              label: '花卉盆栽'
            },
            {
              value: '家具家居',
              label: '家具家居'
            }
          ]
        },
        {
          value: '助农专区',
          label: '助农专区',
          children: [
            {
              value: '时令果蔬',
              label: '时令果蔬'
            },{
              value: '肉禽蛋类',
              label: '肉禽蛋类'
            },
          ]
        }
      ],
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 10, // 每页多少条
        total: 0 // 总记录数
      },
      pageSizes: [10, 20, 30]
    };
  },
  created() {
    this.getGoodsPage()
    this.getSuppliers()
  },
  computed: {
    uploadUrl() {
      return `${this.$store.state.baseUrl}/upload`;
    }
  },
  methods: {
    sortGoodsStatus(a, b) {
      // 如果商品状态不同，按照状态升序排序
      if (a.goodsStatus !== b.goodsStatus) {
        return a.goodsStatus - b.goodsStatus;
      } else {
        // 如果商品状态相同，则将下架状态的商品排在最后
        if (a.goodsStatus === 0) {
          // 如果两个商品都是下架状态，按照其他条件排序（例如商品名称）
          // 如果需要按照其他条件排序，可以修改下面的逻辑
          return a.goodsName.localeCompare(b.goodsName);
        } else {
          return 0; // 其他情况不需要排序
        }
      }
    },
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage
      // 在此刷新数据
      this.getGoodsPage()
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize
      // 在此刷新数据
      this.getGoodsPage()
    },
    getGoodsPage(){
      const data = {
        page:this.tablePage.pageNum,
        size:this.tablePage.pageSize
      }
      queryGoodsPage(data).then(res=>{
        this.goodsList= res.data
        console.log(res)
        this.tablePage.total = res.size
      })
    },
    // 打开编辑商品弹窗
    editGoods(goods) {
      this.currentGoods = {...goods};
      this.dialogVisible = true;
      this.dialogTitle = '编辑商品'
    },
    // 添加商品
    addGoods() {
      this.currentGoods = {};
      this.currentGoods.goodsStatus = '1'
      this.dialogVisible = true;
      this.dialogTitle = '添加新商品'
    },
    // 保存商品（编辑/添加）
    saveGoods() {
      // 在这里可以进行表单验证
      // 保存逻辑，可根据currentGoods中是否有id字段来判断是编辑还是添加
      // 保存成功后关闭弹窗并重新获取商品数据或更新当前商品数据
      if(!this.currentGoods.id){
        console.log(this.currentGoods)
        insertGoods(this.currentGoods).then(res=>{
          console.log(res)
          this.$message.success(res.data.data)
          this.fileList = []
          this.getGoodsPage()
        })
      }else{
        updateGoods(this.currentGoods).then(res=>{
          console.log(res)
          this.$message.success("更新商品数据成功")
          this.getGoodsPage()
        })
      }
      this.dialogVisible = false;

    },
    //级联选择器的时候将最后一级保留
    handleCascaderChange(value) {
      // 将当前选中的最后一级选项的值赋给 currentGoods.tag
      this.currentGoods.tag = value[value.length - 1];
    },
    // 删除商品
    deleteGoods(goods) {
      // 调用后端接口删除商品
      // 删除成功后重新获取商品数据或更新当前商品数据
    },
    // 根据商品状态返回对应的标签类型
    statusTagType(status) {
      return status === '1' ? 'success' : 'danger';
    },
    // 根据商品状态返回对应的文本
    statusText(status) {
      return status === '1' ? '上架' : '下架';
    },
    // 上传图片
    handleUploadSuccess(response, file) {
      if (this.fileList && this.fileList.length > 0) {
        // 如果已经存在文件，更新第一个文件的URL属性
        this.fileList[0].url = this.$store.state.baseUrl + response.result.path;
        console.log(this.fileList)
      } else {
        // 如果文件列表为空，将返回的图片路径添加到文件列表中
        this.fileList = [{ name: file.name, url: this.$store.state.baseUrl + response.result.path }];
        console.log(this.fileList)
      }
      // 将返回的图片路径返回到新增商品的数组中
      this.currentGoods.goodsImage = this.$store.state.baseUrl + response.result.path;
      console.log(this.fileList)
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpg';
      const isPNG = file.type === 'image/png';
      const isJPEG = file.type === 'image/jpeg';
      if (!isJPEG && !isPNG &&!isJPG) {
        this.$message.error('只能上传 JPG 或 PNG 格式的图片');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB');
      }
      return (isJPEG || isPNG) && isLt2M;
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`仅能上传一张图片`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    // 获取供应商信息
    getSuppliers() {
      querySupplier().then(res => {
        this.suppliers = res.data;
      });
    },
  },
};
</script>

<style scoped>
.goods-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
.upload-demo /deep/ .el-upload--text{
  width: 100px;
  height: 30px;
  line-height: 30px;
  background-color: #409EFF;
  color: white;
  border: 0;
}

.upload-demo /deep/ .el-upload__tip{
  line-height: 0;
}
.pagination{
  text-align: center;
}
</style>
